package com.cy.pj.sys.service.realm;

import com.cy.pj.sys.dao.SysUserDao;
import com.cy.pj.sys.pojo.SysUser;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;

//只做认证不做授权      AuthenticatingRealm
//认证和授权都做       AuthorizingRealm

public class ShiroRealm extends AuthorizingRealm {
    @Autowired
    private SysUserDao sysUserDao;

    /**
     * 获取并封装授权信息
     * @param principalCollection
     * @return
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {

            return null;
    }

    /**
     * 获取并封装认证信息
     * @param authenticationToken 封装了客户端认证信息的一个令牌对象
     * @return
     * @throws AuthenticationException
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {

        UsernamePasswordToken upToken = (UsernamePasswordToken) authenticationToken;
        //1,获取客户端提交的用户名
        String username =upToken.getUsername();
        //2,基于用户名查询用户信息并校验
        SysUser sysUser = sysUserDao.selectUserByUserName(username);
        if(sysUser==null)throw new UnknownAccountException();
        //校验,禁止登陆
        if(sysUser.getValid()==0)throw new LockedAccountException();

        //3.封装用户信息 //java 中为属性赋值一般为构造方法或者set方法
        ByteSource credentialsSalt = ByteSource.Util.bytes(sysUser.getSalt());  //左边接口,右边实现类
        return new SimpleAuthenticationInfo(sysUser,     //用户身份
                sysUser.getPassword(),            //已加密的凭证
                credentialsSalt,                //做了编码处理的加密盐对象
                this.getName());                //shiro的name
    }

}
